import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Author YuanYuan
 * @Date 2022/11/28
 * @Time 11:38
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //判断用户名密码是否正确
        try {
            if(null == username || "".equals(username) || null == password || "".equals(password)) {
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("用户名或密码为空");
                return;
            }
            User user = UserDAO.selectByName(username);
            if(null == user) {
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("用户不存在!");
                return;
            }
            if(!password.equals(user.getUserPassword())) {
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("密码错误!");
            }
            //登陆成功创建session
            HttpSession httpSession = req.getSession(true);
            httpSession.setAttribute("user",user);

            resp.setStatus(302);
            resp.sendRedirect("blog_list.html");
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    //判断登录状态
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession httpSession = req.getSession(false);
        //没有session,未登录状态!
        if(null == httpSession) {
            resp.setStatus(403);
            return;
        }
        User user = (User) httpSession.getAttribute("user");
        if(null == user) {
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);
    }
}
